<template>
  <div class="page-container">
    <!-- 公开访问提示 -->
    <div class="public-notice">
      <t-icon name="info-circle" />
      <span>此页面为公开页面，无需登录即可访问</span>
    </div>
    
    <div class="page-header">
      <div class="title">精拓肠道菌群项目样本信息单</div>
    </div>
    
    <div class="page-content">
      <!-- 基本信息 -->
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <div class="section-content">
          <t-cell-group>
            <t-field
              v-model="formData.name"
              label="姓名"
              placeholder="请输入您的姓名"
              :error-message="errors.name"
              @blur="validateField('name')"
            />
            
            <t-field label="性别">
              <template #input>
                <t-radio-group v-model="formData.gender" @change="validateField('gender')">
                  <t-radio value="男">男</t-radio>
                  <t-radio value="女">女</t-radio>
                </t-radio-group>
              </template>
            </t-field>
            
            <t-field
              v-model.number="formData.age"
              type="number"
              label="年龄"
              placeholder="请输入年龄"
              :error-message="errors.age"
              @blur="validateField('age')"
            />
            
            <t-field label="体重">
              <template #input>
                <div class="weight-input">
                  <t-input
                    v-model.number="formData.weight"
                    type="number"
                    placeholder="请输入体重"
                    :error-message="errors.weight"
                    @blur="validateField('weight')"
                  />
                  <span class="unit">kg</span>
                </div>
              </template>
            </t-field>
            
            <t-field
              v-model="formData.sampleNumber"
              label="样本编号"
              placeholder="请输入样本编号"
              :error-message="errors.sampleNumber"
              @blur="validateField('sampleNumber')"
            />
            
            <t-field
              v-model="formData.contactPhone"
              label="联系方式"
              placeholder="请输入联系电话"
              :error-message="errors.contactPhone"
              @blur="validateField('contactPhone')"
            />
            
            <t-field
              v-model="formData.sampleDate"
              label="样本采集日期"
              placeholder="请选择日期"
              readonly
              :error-message="errors.sampleDate"
              @click="showDatePicker = true"
            />
          </t-cell-group>
        </div>
      </div>
      
      <!-- 饮食习惯 -->
      <div class="form-section">
        <div class="section-title">饮食习惯</div>
        <div class="section-content">
          <div class="diet-question">
            <div class="question-text">
              1. 您每周的饮食是否包含以下种类（新鲜来源，非加工食品）（可多选）：
            </div>
            <t-checkbox-group v-model="formData.dietaryHabits" class="diet-options">
              <t-checkbox value="蔬菜">蔬菜</t-checkbox>
              <t-checkbox value="水果">水果</t-checkbox>
              <t-checkbox value="肉类">肉类</t-checkbox>
              <t-checkbox value="海鲜">海鲜</t-checkbox>
            </t-checkbox-group>
          </div>
        </div>
      </div>
      
      <!-- 备注信息 -->
      <div class="form-section">
        <div class="section-title">备注信息</div>
        <div class="section-content">
          <t-textarea
            v-model="formData.remarks"
            placeholder="请输入其他需要说明的信息（选填）"
            :maxlength="200"
            indicator
          />
        </div>
      </div>
    </div>
    
    <div class="submit-button">
      <t-button
        theme="primary"
        size="large"
        :loading="isSubmitting"
        @click="handleSubmit"
      >
        {{ isSubmitting ? '提交中...' : '提交' }}
      </t-button>
    </div>
    
    <!-- 日期选择器 -->
    <t-date-time-picker
      v-model="showDatePicker"
      :value="formData.sampleDate"
      mode="date"
      title="选择样本采集日期"
      @confirm="handleDateConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  CellGroup as TCellGroup,
  Field as TField,
  Input as TInput,
  Button as TButton,
  RadioGroup as TRadioGroup,
  Radio as TRadio,
  CheckboxGroup as TCheckboxGroup,
  Checkbox as TCheckbox,
  Textarea as TTextarea,
  DateTimePicker as TDateTimePicker,
  Toast,
  Dialog
} from 'tdesign-mobile-vue'
import { useFormStore } from '@/store/form'
import { formApi } from '@/api/form'
import { formatDate } from '@/utils'

const router = useRouter()
const formStore = useFormStore()

// 表单数据
const formData = computed(() => formStore.formData)
const isSubmitting = computed(() => formStore.isSubmitting)

// 日期选择器显示状态
const showDatePicker = ref(false)

// 表单验证错误信息
const errors = reactive({
  name: '',
  gender: '',
  age: '',
  weight: '',
  sampleNumber: '',
  contactPhone: '',
  sampleDate: ''
})

// 验证单个字段
const validateField = (field: string) => {
  errors[field] = ''
  
  switch (field) {
    case 'name':
      if (!formData.value.name.trim()) {
        errors.name = '请输入姓名'
      }
      break
    case 'gender':
      if (!formData.value.gender) {
        errors.gender = '请选择性别'
      }
      break
    case 'age':
      if (!formData.value.age || formData.value.age <= 0) {
        errors.age = '请输入有效年龄'
      }
      break
    case 'weight':
      if (!formData.value.weight || formData.value.weight <= 0) {
        errors.weight = '请输入有效体重'
      }
      break
    case 'sampleNumber':
      if (!formData.value.sampleNumber.trim()) {
        errors.sampleNumber = '请输入样本编号'
      }
      break
    case 'contactPhone':
      if (!formData.value.contactPhone.trim()) {
        errors.contactPhone = '请输入联系方式'
      } else if (!/^1[3-9]\d{9}$/.test(formData.value.contactPhone)) {
        errors.contactPhone = '请输入有效的手机号码'
      }
      break
    case 'sampleDate':
      if (!formData.value.sampleDate) {
        errors.sampleDate = '请选择样本采集日期'
      }
      break
  }
}

// 日期选择确认
const handleDateConfirm = (value: string) => {
  formStore.updateFormData({ sampleDate: formatDate(value) })
  showDatePicker.value = false
  validateField('sampleDate')
}

// 提交表单
const handleSubmit = async () => {
  // 验证所有字段
  const fields = ['name', 'gender', 'age', 'weight', 'sampleNumber', 'contactPhone', 'sampleDate']
  fields.forEach(field => validateField(field))
  
  // 检查是否有错误
  const hasErrors = Object.values(errors).some(error => error !== '')
  if (hasErrors) {
    Toast({
      theme: 'error',
      message: '请检查并完善表单信息'
    })
    return
  }
  
  try {
    formStore.setSubmitting(true)
    
    // 调用API提交表单
    await formApi.submitForm(formData.value)
    
    formStore.setSubmitSuccess(true)
    
    Toast({
      theme: 'success',
      message: '提交成功！'
    })
    
    // 跳转到成功页面
    router.push('/success')
    
  } catch (error) {
    console.error('提交失败:', error)
    Toast({
      theme: 'error',
      message: '提交失败，请重试'
    })
  } finally {
    formStore.setSubmitting(false)
  }
}
</script>

<style lang="less" scoped>
.public-notice {
  background-color: #e7f3ff;
  border: 1px solid #b3d8ff;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #0052d9;
  
  :deep(.t-icon) {
    font-size: 16px;
  }
}

.weight-input {
  display: flex;
  align-items: center;
  
  .unit {
    margin-left: 8px;
    color: #666;
    font-size: 14px;
  }
}

.diet-question {
  .question-text {
    font-size: 14px;
    color: #000;
    margin-bottom: 16px;
    line-height: 1.5;
  }
  
  .diet-options {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
  }
}

:deep(.t-field__label) {
  min-width: 80px;
}

:deep(.t-radio-group) {
  display: flex;
  gap: 24px;
}

:deep(.t-checkbox) {
  margin-right: 0;
}
</style>